package com.bdqn.ch06.controller;

import com.bdqn.ch06.entity.Right;
import com.bdqn.ch06.entity.Role;
import com.bdqn.ch06.entity.User;
import com.bdqn.ch06.service.RoleService;
import com.bdqn.ch06.service.UserService;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Resource
    UserService userService;

    @Resource
    RoleService roleService;

    @GetMapping(value = "/login")
    public String login() {
        return "login";
    }

    @GetMapping(value = "/main")
    public String main() {
        return "main";
    }

    @GetMapping(value = "/403")
    public String unauth() {
        return "403";
    }

    @GetMapping(value = "/remember")
    public String remember() {
        return "remember";
    }

    @GetMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("sessionuser");
        session.invalidate();
        SecurityUtils.getSubject().logout();
        return "redirect:login";
    }

    @PostMapping(value = "/dologin")
    public String dologin(@RequestParam(value = "usrName") String usrName,
                          @RequestParam(value = "usrPassword") String usrPassword,
                          @RequestParam(value = "rememberMe", required = false) String rememberMe,
                          Model model,
                          HttpSession session) {

        /*User user = userService.findByUserNameBiz(usrName);
        if (user == null) {
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } else {
            if (!user.getUsrPassword().equals(usrPassword)) {
                model.addAttribute("msg", "密码错误");
                return "login";
            } else {
                session.setAttribute("sessionuser", user);
                return "main";
            }
        }*/
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);

            if (rememberMe != null) {
                token.setRememberMe(true); //设置记住我登录
            }

            Subject subject = SecurityUtils.getSubject();
            subject.login(token);//认证、登录
            //认证(登录)成功
            User user = (User) subject.getPrincipal();
            Role role = user.getRole(); //如果一对多关联不是立即加载，则需要通过用户获取角色
            List<Right> rights = roleService.findRightsByRole(role);
            role.getRights().addAll(rights);
            session.setAttribute("sessionuser", user);
            return "redirect:/main";//建议重定向
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("msg", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("msg", "用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("msg", "认证异常，登录失败！");
            return "login";
        }
    }
}
